package com.sk.weichat.view;

import android.content.Context;
import android.graphics.Matrix;
import android.graphics.SurfaceTexture;
import android.opengl.GLES20;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.NestedScrollingChild2;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import fm.jiecao.jcvideoplayer_lib.JCResizeTextureView;

/**
 * Created by lzs on 2018/12/20 12:54
 * E-Mail Address：343067508@qq.com
 */
public class PlayTextureView extends FrameLayout {

    private static final String TAG = "PlayTextureView";

    public JCResizeTextureView getTextureView() {
        return mTextureView;
    }

    private JCResizeTextureView mTextureView;
    private TextureView.SurfaceTextureListener mSurfaceTextureListener;
    private int mVideoWidth;
    private int mVideoHeight;
    private SurfaceTexture mSurfaceTexture;

    public PlayTextureView(@NonNull Context context) {
        this(context, null);
    }

    public PlayTextureView(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public PlayTextureView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    public void init() {
        initTextureView();
    }

    private void initTextureView() {
//        mTextureView = new TextureView(getContext());
        mTextureView = new JCResizeTextureView(getContext());
        mTextureView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
//        mTextureView.addOnLayoutChangeListener(new OnLayoutChangeListener() {
//            @Override
//            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
//                if (mVideoWidth != 0 && mVideoHeight != 0) {
//
//                    setVideoCenter(mTextureView.getWidth(), mTextureView.getHeight(), mVideoWidth, mVideoHeight);
//                }
//            }
//        });
        mSurfaceTexture = newSurfaceTexture();
        mTextureView.setSurfaceTexture(mSurfaceTexture);

        mTextureView.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {
            @Override
            public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
                Log.e("lzs", "PlayTextureView onSurfaceTextureAvailable");
                if (mSurfaceTextureListener != null) {
                    Log.e("lzs", "PlayTextureView onSurfaceTextureAvailable mSurfaceTextureListener is not null");
                    mSurfaceTextureListener.onSurfaceTextureAvailable(surface, width, height);
                }
            }

            @Override
            public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
                Log.e("lzs", "PlayTextureView onSurfaceTextureSizeChanged");
                if (mSurfaceTextureListener != null) {
                    mSurfaceTextureListener.onSurfaceTextureSizeChanged(surface, width, height);
                }
            }

            @Override
            public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
                if (mSurfaceTextureListener != null) {
                    return mSurfaceTextureListener.onSurfaceTextureDestroyed(surface);
                }
                //
                return true;
            }

            @Override
            public void onSurfaceTextureUpdated(SurfaceTexture surface) {

                if (mSurfaceTextureListener != null) {
                    mSurfaceTextureListener.onSurfaceTextureUpdated(surface);
                }
            }
        });

        mTextureView.setVisibility(View.VISIBLE);
        addView(mTextureView, 0);

        //Log.e("lzs", "addview");
    }

    //视频居中播放
    private void setVideoCenter(float viewWidth, float viewHeight, float videoWidth, float videoHeight) {

        Matrix matrix = new Matrix();
        float sx = viewWidth / videoWidth;
        float sy = viewHeight / videoHeight;
        float maxScale = Math.max(sx, sy);

        matrix.preTranslate((viewWidth - videoWidth) / 2, (viewHeight - videoHeight) / 2);
        matrix.preScale(videoWidth / viewWidth, videoHeight / viewHeight);
        matrix.postScale(maxScale, maxScale, viewWidth / 2, viewHeight / 2);

        mTextureView.setTransform(matrix);
        mTextureView.postInvalidate();
    }

    public void resetTextureView() {
        onPlayTextureViewTouchListener = null;
        resetTextureView(null);
    }

    public void resetTextureView(SurfaceTexture surfaceTexture) {
        Log.e("lzs", "resetTextureView");
        removeView(mTextureView);
        //initTextureView(surfaceTexture);
    }

    public void setVideoSize(int videoWidth, int videoHeight) {
        this.mVideoWidth = videoWidth;
        this.mVideoHeight = videoHeight;
    }

    public void setSurfaceTextureListener(TextureView.SurfaceTextureListener surfaceTextureListener) {
        this.mSurfaceTextureListener = surfaceTextureListener;
    }

    //初始化SurfaceTexture
    private SurfaceTexture newSurfaceTexture() {
        int[] textures = new int[1];
        GLES20.glGenTextures(1, textures, 0);
        int texName = textures[0];
        SurfaceTexture surfaceTexture = new SurfaceTexture(texName);
        surfaceTexture.detachFromGLContext();
        return surfaceTexture;
    }

    public SurfaceTexture getSurfaceTexture() {
        //mSurfaceTexture.isReleased() NoSuchMethodError No virtual method isReleased()Z in class Landroid/graphics/SurfaceTexture
        if (mSurfaceTexture != null) {
            return mSurfaceTexture;
        }
        return null;
    }

    private long mFirstTouchEventTime;
    private int mDownX;
    private int mUpX;
    private int mDownY;
    private int mUpY;

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {

        return super.dispatchTouchEvent(event);
    }

//    @Override
//    public boolean onTouchEvent(MotionEvent event) {
//        if (event.getAction() == MotionEvent.ACTION_DOWN) {
//            mDownX = (int) event.getX();
//            mDownY = (int) event.getY();
//            Log.e(TAG, "mDownX>" + mUpX + "  mDownX>" + mDownX);
//            if (mFirstTouchEventTime == 0) {
//                mFirstTouchEventTime = event.getDownTime();
//            }
//        } else if (event.getAction() == MotionEvent.ACTION_UP) {
//            mUpX = (int) event.getX();
//            mUpY = (int) event.getY();
//            Log.e(TAG, "mFirstTouchEventTime>>>" + mFirstTouchEventTime + "   upTouchEventTime>>" + event.getEventTime());
//            if (Math.abs(mUpX - mDownX) < 5 && Math.abs(mUpY - mDownY) < 5) {
//                if (Math.abs(mFirstTouchEventTime - event.getEventTime()) < 300) {
//                    if (onPlayTextureViewTouchListener != null) {
//                        Log.e(TAG, "onSingleTap");
//                        onPlayTextureViewTouchListener.onSingleTap();
//                    } else {
//                        Log.e(TAG, "onPlayTextureViewTouchListener is null");
//                    }
//                    //单击
//
//                } else {
//                }
//            } else {
//
//            }
//            mFirstTouchEventTime = 0L;
//        }
//        return super.onTouchEvent(event);
//    }

    private OnPlayTextureViewTouchListener onPlayTextureViewTouchListener;


    public void setOnPlayTextureViewTouchListener(OnPlayTextureViewTouchListener onPlayTextureViewTouchListener) {
        this.onPlayTextureViewTouchListener = onPlayTextureViewTouchListener;
    }

    public OnPlayTextureViewTouchListener getOnPlayTextureViewTouchListener() {
        return onPlayTextureViewTouchListener;
    }

    public interface OnPlayTextureViewTouchListener {
        void onSingleTap();
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        onPlayTextureViewTouchListener = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            if (mSurfaceTexture != null && !mSurfaceTexture.isReleased()) {
                mSurfaceTexture.release();
            }
        } else {
            if (mSurfaceTexture != null) {
                mSurfaceTexture.release();
            }
        }
    }
}
